{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cell(size, residual, reuse=False):\n",
    "            c = tf.nn.rnn_cell.LSTMCell(size,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "            if residual:\n",
    "                c = tf.nn.rnn_cell.ResidualWrapper(c)\n",
    "            return c\n",
    "        \n",
    "        def cells(size = size_layer, residual = 1, reuse=False):\n",
    "            cell_list = []\n",
    "            for i in range(num_layers):\n",
    "                cell_list.append(cell(size, i >= residual, reuse=reuse))\n",
    "            return cell_list\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells(reuse=reuse)), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells()), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-98cb660624c9>:12: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-98cb660624c9>:42: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-98cb660624c9>:45: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[  550, 16178, 30935, 19914,  7969,  3842, 25245, 21716,  5951,\n",
       "         23121,  7843, 19285, 29343,  3512, 12827, 17261, 22834, 16377,\n",
       "          7956, 31374, 27619, 27619,  3971,  8356, 22652, 28710, 10778,\n",
       "          8320, 29746, 30612, 30069, 27202,  7921, 13627, 10458, 18455,\n",
       "          3734,  4038, 13534,  4038, 20626,  9384, 19846, 19846, 20432,\n",
       "         13803, 12925, 19693, 18837, 18837,  6733, 21716, 21716,  8643,\n",
       "         17845,  2382,  2100,  2100, 21323, 19530, 19530, 10818, 10453,\n",
       "           170, 10453,  3311, 21309, 17949, 16680, 31154, 29434, 29285],\n",
       "        [ 9418,  9418,  9418,  9418,  9418,  9418, 28244,  7893, 20489,\n",
       "         20489, 24536,  7244,  8562,  7244,  6563,  6563, 29549, 14523,\n",
       "          6563,  8362, 21870, 28339,  2679, 20224,  7760, 16111, 14842,\n",
       "         13538, 14097, 14097, 10981, 14097, 14097,  3331, 23235, 13295,\n",
       "         10198, 10198, 29897,  8509, 16369,  1093, 14166,   925, 12512,\n",
       "          8605, 12512, 28037, 12828, 12600, 20725, 16809, 20185, 20725,\n",
       "         13925,  3345, 24411, 24411, 29342,  4104, 13925, 13925,  8083,\n",
       "         30678,  7786,  7786,  1910,  1910, 25680, 27728,  1910, 25680],\n",
       "        [10241, 17084, 31811, 19739,  7089,  7990,  7990, 29000, 29000,\n",
       "           263,   263, 15445,  4941, 11156,  3691, 10092,  6314, 29087,\n",
       "         10245, 29500,  5202, 18170, 11795, 29409, 30081, 29409, 13454,\n",
       "         13454, 16098,  9316,  9316, 27406, 27406,  4293, 12557, 12597,\n",
       "         15241, 11061, 11061, 30432, 11061, 30432, 11061, 11061, 30432,\n",
       "         16884, 22329, 13382, 15177, 15177, 11061, 11061, 11061, 22238,\n",
       "         19785, 19785, 30283, 30283, 15868, 20266, 15868,   835, 12156,\n",
       "         16458, 16458, 20014, 17116, 22442, 22245, 27731, 21983, 21983],\n",
       "        [26261, 22474, 22254, 12511, 14733, 14580, 12349,  1608,  5819,\n",
       "          2913,  2913,  2913,  2913,  2913,  2913,  2913, 26172,  2913,\n",
       "          2913, 26172,  2913,  2913,  2913, 26172,  2913,  2913,  2913,\n",
       "         26172,  2913,  2913, 26172,  2913,  2913, 26172,  2913,  2913,\n",
       "         26172,  2913,  2913, 26172,  2913,  2913, 26172,  2913,  2913,\n",
       "         26172,  2913,  2913, 26172,  2913,  2913, 26172,  2913, 26172,\n",
       "          2913,  2913, 26172,  2913,  2913, 26172,  2913, 26172,  2913,\n",
       "          2913, 26172,  2913,  2913, 26172,  2913, 26172,  2913,  2913],\n",
       "        [28008, 29697, 29697, 17430, 17430, 31573, 14060, 12075, 28255,\n",
       "         27331, 27331, 27331,  6300,  6300,  5389,   305, 13520,  3213,\n",
       "         27892,  5267,  5267,  8533,  8533, 14667, 26443, 26443, 10931,\n",
       "          8113, 19013, 13806, 22255, 12908, 13773, 30347, 30347,   432,\n",
       "         12295,  8764,  8114,  8114,  8114,  8114,  1690, 12447, 12447,\n",
       "         31180, 12447, 31180, 31273, 31273, 12413,  6515,  6515, 24317,\n",
       "         24317, 30300, 25617, 25617, 14465, 15900,  7183,  7183, 20910,\n",
       "         21478, 20910,  6631, 26421,  4965, 20910, 20910,  6631, 25326],\n",
       "        [ 6114,  6114,  6114,  3682, 13692, 13692,   288, 18157, 11648,\n",
       "          9007,  9007, 11029, 13579,  5308,  5526, 21512,  5021,  2340,\n",
       "         16930,  2340,  2548,  2548, 30638, 25170, 20467, 26673, 26673,\n",
       "          7801, 26673,  7801,  2208,  2208,  9996, 29969, 19917, 19917,\n",
       "         25179, 25179, 20043, 13915, 20043, 13830,   290, 24096, 18730,\n",
       "         24096,  9282,  8589, 28010, 30223, 25996, 25996,   290, 28010,\n",
       "         28010, 21852,  4668, 28562, 25996, 21897, 27631, 16704, 31069,\n",
       "         29795, 14687,  7718, 15449,  8908,  8908, 13371, 17834, 17834],\n",
       "        [14672, 14672, 31716,  8949, 27030, 26436, 26436, 26436, 19933,\n",
       "         26828, 14098, 21323, 13610, 14371, 27848, 13375, 13375, 30609,\n",
       "         28009, 28009,  4570, 25128, 21315, 11023, 31417, 20491, 19578,\n",
       "         20349, 18170, 12675, 18535, 26001, 26001, 26001, 26001, 26001,\n",
       "         26001, 24361, 30246,  7023, 30246, 26770, 30606, 22524, 22524,\n",
       "         22524, 22524, 22524, 17543, 28252,  1541, 28252, 28252,  2026,\n",
       "          8312,  3262, 16879, 16879,  5960, 31565, 31565, 25274, 28383,\n",
       "          1311,  2331,  4038, 22628, 12019,  1311,  2331,  3150,  3150],\n",
       "        [ 2225, 13157,  8859,  7927,  8842, 17006, 17006, 17006,  5822,\n",
       "         17006, 30187, 27029, 27029, 19818,  2020,  2020,  2230, 19173,\n",
       "         25204,  3687, 15523, 20912, 16499, 20221,  6415, 25982, 11286,\n",
       "         11286,  4313,  1224, 19456, 16668, 16049, 15575, 19038, 29184,\n",
       "         29184, 16049, 21914,  4991,  3861, 16141, 24213, 24213, 19818,\n",
       "          6563, 20913,  2155, 14080,  7918, 17947,  7918, 12807, 23865,\n",
       "         30732,  4495, 30654, 17511, 11286,  5906, 24755, 26169,  3355,\n",
       "         25259, 18085, 27168, 18085, 16631,  1076,  1076,  7329, 30984],\n",
       "        [ 8394, 13038, 24975, 13396, 15602,  5994,  6394, 11879,   548,\n",
       "          6719, 17534, 17534, 14534, 14534,  5464, 22449,  5467,    74,\n",
       "          5467, 22060,  9590,  7397, 27087,  9214, 10826,  5454, 16578,\n",
       "          5053, 16555, 31254, 10012, 31254,  1328, 19360, 22533, 12998,\n",
       "         18989, 21810, 27390, 18989, 16342, 16342,  4983,  8947, 23785,\n",
       "         11101, 14988, 11598, 11598,  3198, 14000,  3198, 25237, 27450,\n",
       "         31116, 16168, 27699, 27699, 18626, 31410, 29678, 27696, 29003,\n",
       "         11093, 11093, 13026, 21175, 21886, 20771, 22071, 30598, 30598],\n",
       "        [14579, 14579,  3791,  3791,  8491, 26347, 31673,  9242, 26296,\n",
       "          2484, 23307, 27739,  4488,  5750, 21828,  5845,  9316,  9316,\n",
       "          9316, 31997, 15983, 23246,  5837, 13298, 11599, 25429, 25429,\n",
       "         25880, 20183, 11251, 11251, 19098,  5245,  7399, 21000, 10481,\n",
       "          2737,  2737,  2088,  2088, 24504, 26736, 26736, 26736, 12752,\n",
       "          2723, 30066, 16284, 13025, 27377, 26213, 12407, 18854, 23246,\n",
       "         20058,  6974, 14883, 17249, 17249, 13989, 17328, 16157,  8591,\n",
       "         12939, 14479, 12939, 29829, 12939, 29829, 29829, 17564,  8399]],\n",
       "       dtype=int32), 10.373791, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.417, cost=3.42]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.87it/s, accuracy=0.478, cost=3.03]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.633968, training avg acc 0.294278\n",
      "epoch 1, testing avg loss 3.359161, testing avg acc 0.422863\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.532, cost=2.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.532, cost=2.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 2.920883, training avg acc 0.471491\n",
      "epoch 2, testing avg loss 2.793046, testing avg acc 0.489492\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.594, cost=2.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.575, cost=2.34]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.390187, training avg acc 0.535585\n",
      "epoch 3, testing avg loss 2.625663, testing avg acc 0.512862\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.645, cost=1.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.559, cost=2.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.074792, training avg acc 0.577210\n",
      "epoch 4, testing avg loss 2.597547, testing avg acc 0.516676\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:17<00:00,  2.31it/s, accuracy=0.695, cost=1.42]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.09it/s, accuracy=0.581, cost=2.28]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 1.843370, training avg acc 0.610288\n",
      "epoch 5, testing avg loss 2.611597, testing avg acc 0.522405\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.729, cost=1.2] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.554, cost=2.42]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.657485, training avg acc 0.638165\n",
      "epoch 6, testing avg loss 2.712914, testing avg acc 0.519586\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.769, cost=1.01]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.532, cost=2.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.504109, training avg acc 0.662243\n",
      "epoch 7, testing avg loss 2.820680, testing avg acc 0.513849\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.788, cost=0.904]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.01it/s, accuracy=0.565, cost=2.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.377079, training avg acc 0.682809\n",
      "epoch 8, testing avg loss 2.878387, testing avg acc 0.512292\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.801, cost=0.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.527, cost=2.65]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.265738, training avg acc 0.701797\n",
      "epoch 9, testing avg loss 2.986423, testing avg acc 0.504479\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.821, cost=0.703]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.00it/s, accuracy=0.532, cost=2.64]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.168777, training avg acc 0.718569\n",
      "epoch 10, testing avg loss 3.109720, testing avg acc 0.510188\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.837, cost=0.63] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  5.00it/s, accuracy=0.5, cost=2.92]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.085713, training avg acc 0.733793\n",
      "epoch 11, testing avg loss 3.232621, testing avg acc 0.504903\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.867, cost=0.541]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  5.00it/s, accuracy=0.543, cost=2.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.010832, training avg acc 0.747390\n",
      "epoch 12, testing avg loss 3.330807, testing avg acc 0.502566\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.858, cost=0.513]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.522, cost=3.19]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.949620, training avg acc 0.758911\n",
      "epoch 13, testing avg loss 3.441218, testing avg acc 0.496420\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.863, cost=0.507]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.516, cost=3.13]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.902964, training avg acc 0.767248\n",
      "epoch 14, testing avg loss 3.519819, testing avg acc 0.493839\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.862, cost=0.537]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.505, cost=3.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.856758, training avg acc 0.776377\n",
      "epoch 15, testing avg loss 3.619400, testing avg acc 0.486771\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.885, cost=0.429]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.543, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.820027, training avg acc 0.783259\n",
      "epoch 16, testing avg loss 3.682382, testing avg acc 0.493822\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.887, cost=0.406]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.538, cost=3.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.772294, training avg acc 0.793522\n",
      "epoch 17, testing avg loss 3.795274, testing avg acc 0.492438\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.897, cost=0.382]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.554, cost=3.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.738153, training avg acc 0.800307\n",
      "epoch 18, testing avg loss 3.880716, testing avg acc 0.491811\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.908, cost=0.362]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.522, cost=3.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.709731, training avg acc 0.805891\n",
      "epoch 19, testing avg loss 3.983512, testing avg acc 0.488204\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:12<00:00,  2.32it/s, accuracy=0.914, cost=0.333]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.522, cost=3.46]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.687741, training avg acc 0.810447\n",
      "epoch 20, testing avg loss 4.050674, testing avg acc 0.489076\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:20<00:00,  1.99it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.15493448"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
